package com.sczmgk.hotline_pzh.hxim;

import com.sczmgk.hotline_pzh.annotation.CompareName;

import java.lang.reflect.Field;
import java.util.Comparator;

/**
 * Created by Administrator on 2016/12/5.
 */

//public class  ChatMessageComparator implements Comparator<ChatMsgBean>{
//
//        @Override
//        public int compare(ChatMsgBean chatMessage, ChatMsgBean t1) {
//            long time1 = Long.valueOf(chatMessage.getMsgtime());
//            long time2 = Long.valueOf(t1.getMsgtime());
//            return (int) (time1 - time2);
//        }
//
//}


public  class ChatMessageComparator<T> implements Comparator<T> {


    public int compare(T chatMessage, T t1) {
        long time1 = Long.valueOf(getMsgtime(chatMessage));
        long time2 = Long.valueOf(getMsgtime(t1));
        return (int) (time1 - time2);
    }

    private long getMsgtime(T t) {

        long msgtime = 0;
        Class<?> clazz = t.getClass();//得到字节码
        try {
            String fieldName = null;
            CompareName annotation = clazz.getAnnotation(CompareName.class);
            if (annotation != null) {
                fieldName = annotation.value();
                if (fieldName != null) {
                    Field field = clazz.getDeclaredField(fieldName);//通过反射拿到字段
                    field.setAccessible(true);
                    msgtime = (long) field.get(t);//这个方法是将字段内容取出自某个对象
                    return msgtime;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return msgtime;
        }
        return msgtime;
    }
}
